var authUserName = "dhwebservice";
var authPwd = "Nog9D%9V";
var namespace = 'http://www.dhcc.com.cn'; //命名空间和服务端保持一致 否则报400
var actionUrl = 'http:/Nur.MNIS.Service.WebService'; //soap协议使用http 无需适配 否则报500
// var webServiceURl = "http://10.1.20.197/imedical/web/Nur.MNIS.Service.WebService.cls"
// var webServiceURl = "http://localhost:1443/imedical/webservice/Nur.MNIS.Service.WebService.cls"
var webServiceURl = "http://10.1.20.152:1443/imedical/webservice/Nur.MNIS.Service.WebService.cls"
// var webServiceURl = "https://82.157.186.213:1443/imedical/webservice/Nur.MNIS.Service.WebService.cls"
//var webServiceURl = "https://110.40.226.191:1443/imedical/webservice/Nur.NBS.Service.WebService.cls";

var xhr = null;
var WebService = function () {
}
//解析xml
WebService.prototype.parseXML = function (data) {
    var xml;
    if (!data || typeof data !== "string") {
        return null;
    }
    // 只支持: IE 9 - 11 only
    try {
        xml = (new window.DOMParser()).parseFromString(data, "text/xml");
    } catch (e) {
        xml = undefined;
    }
    if (!xml || xml.getElementsByTagName("parsererror").length) {
        throw new Error("Invalid XML: " + data);
    }
    return xml;
};

//请求回调
WebService.prototype.onreadystatechange = function (method, callBack) {
    var _this = this;
    xhr.onreadystatechange = function () {
        if (!xhr) {
            console.log("xhr: " + xhr)
            return;
        }
        console.log("State: " + xhr.readyState)
        if (xhr.readyState == 4) {
            if (xhr.status == 200) {
                console.log("xhr请求成功：");
                var resultStr = xhr.responseText;
                if (resultStr == null || resultStr == '') {
                    console.log('fail:响应数据为空!');
                    callBack && callBack('fail:响应数据为空!')
                    xhr = null;
                    return;
                }
                if (resultStr.indexOf('<' + method + 'Result>') != -1 && resultStr.indexOf('</' + method + 'Result>') != -1) {
                    // var dataXML = jQuery.parseXML(resultStr);
                    var dataXML = _this.parseXML(resultStr);
                    var destEle = dataXML.getElementsByTagName(method + 'Result');
                    var result = destEle[0].firstChild.nodeValue;
                    var resultObj = eval('(' + result + ')');
                    callBack && callBack(resultObj)
                    // setTimeout(function () {
                    //     xhr = null;
                    //     console.log('xhr:置为为空!');
                    // }, 60000)
                } else {
                    console.log('fail:数据格式不正确');
                    callBack && callBack('fail:数据格式不正确')
                    xhr = null;
                }
            } else {
                console.log("fail:xhr请求失败：" + xhr.readyState);
                callBack && callBack("fail:请求失败：" + xhr.readyState)
                xhr = null;
            }
        }
    }
}
//发送请求
WebService.prototype.request = function (method, paramDict, callBackReq) {
    //回调
    this.onreadystatechange(method, callBackReq);

    //POST请求
    xhr.open("POST", webServiceURl, true);

    //固定参数
    var docsUrl = 'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-';
    var orgUrl = 'http://www.w3.org/2001/XMLSchema';
    var schemasUrl = 'http://schemas.xmlsoap.org/';

    /******************参数组合***********************/
    var paramStr = '<' + method + ' xmlns="' + namespace + '">';
    if (paramDict != null) {
        for (var keyStr in paramDict) {
            var valueStr = paramDict[keyStr];
            paramStr += '<' + keyStr + '>' + valueStr + '</' + keyStr + '>'
        }
    }
    paramStr += '</' + method + '>';

    /******************报文组合***********************/
    var headAction = '<wsa:Action>' + actionUrl + '.' + method + '</wsa:Action>';
    var headAddress = '<wsa:Address>' + schemasUrl + 'ws/2004/08/addressing/role/anonymous</wsa:Address>';
    var replyTo = '<wsa:ReplyTo>' + headAddress + '</wsa:ReplyTo>';
    var wsaTo = '<wsa:To>' + webServiceURl + '</wsa:To>'
    var username = '<wsse:Username>' + authUserName + '</wsse:Username>';
    var pwd = '<wsse:Password Type="' + docsUrl + 'username-token-profile-1.0#PasswordText">' + authPwd + '</wsse:Password>';
    var usernameToken = '<wsse:UsernameToken xmlns:wsu="' + docsUrl + 'wssecurity-utility-1.0.xsd">' + username + pwd + '</wsse:UsernameToken>';
    var security = '<wsse:Security soap:mustUnderstand="1">' + usernameToken + '</wsse:Security>';
    var soapHeader = '<soap:Header>' + headAction + replyTo + wsaTo + security + "</soap:Header>";
    var soapBody = '<soap:Body>' + paramStr + '</soap:Body>';
    var data = '<?xml version="1.0" encoding="utf-8"?>' +
        '<soap:Envelope xmlns:xsi="' + orgUrl + '-instance" ' +
        'xmlns:xsd="' + orgUrl + '" ' +
        'xmlns:soap="' + schemasUrl + 'soap/envelope/" ' +
        'xmlns:wsa="' + schemasUrl + 'ws/2004/08/addressing" ' +
        'xmlns:wsse="' + docsUrl + 'wssecurity-secext-1.0.xsd" ' +
        'xmlns:wsu="' + docsUrl + 'wssecurity-utility-1.0.xsd">' +
        soapHeader +
        soapBody +
        '</soap:Envelope>';
    xhr.setRequestHeader('Content-Type', "text/xml; charset=utf-8");
    xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
    xhr.setRequestHeader("SOAPAction", namespace + '/' + method);
    // 发送HTTP请求
    //console.log(data)
    xhr.send(data);
}

WebService.prototype.post = function (method, params, callBack) {
    var med = "RequestData"
    var p = JSON.stringify(params);
    console.log("方法:" + method + ",参数:" + p);
    var paramDict = {
        "method": method,
        "params": p,
        "version": "3.3"
    }
    xhr = null;
    if (window.XMLHttpRequest) {
        xhr = new XMLHttpRequest();
        this.request(med, paramDict, callBack)
    } else if (window.ActiveXObject) {
        xhr = new ActiveXObject("Microsoft.XMLHTTP");
        this.request(med, paramDict, callBack)
    }
}
WebService.prototype.postPlus = function (method, params, callBack) {
    if (window.android) {
        var content = JSON.stringify({
            params: params,
            method: method,
            version: "3.3"
        })
        window.android.callAndroid(content, "request");
    } else {
        this.post(method, params, callBack)
    }
}
//显示加载
WebService.prototype.showLoading = function (_this) {
    if (window.android) {
        window.android.callAndroid("show", "loading");
    } else {
        if (_this && _this.$indicator) {
            _this.$indicator.open('加载中...');
        }
    }
};
//隐藏加载
WebService.prototype.hideLoading = function (_this) {
    if (window.android) {
        window.android.callAndroid("", "loading");
    } else {
        if (_this && _this.$indicator) {
            _this.$indicator.close('加载中...');
        }
    }
};
//获取对象
var Http = new WebService()

// 测试登录
// var params = {password: "1", logonWardId: "", userCode: "hs01"}
// Http.post("Logon", params)
